using System;

namespace Magic.Core
{
	/// <summary>
	/// Specifies a binary byte order to use when reading or writing values.
	/// </summary>
	public enum ByteOrder : sbyte
	{
		LittleEndian = 0,
		BigEndian = 1
	}

	/// <summary>
	/// Contains static methods to swap values in byte order.
	/// </summary>
	public sealed class EndianSwap
	{
        public static long SwapToInt64(byte[] buf, ByteOrder order)
		{
            if(order == ByteOrder.BigEndian)
			return (buf[0]<<56) |(buf[1]<<48) |(buf[2]<<40) |(buf[3]<<32) |(buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
            else
			return (buf[7]<<56) |(buf[6]<<48) |(buf[5]<<40) |(buf[4]<<32) |(buf[3]<<24) | (buf[2]<<16) | (buf[1]<<8) | buf[0];

		}
        public static int SwapToInt32(byte[] buf, ByteOrder order)
        {
            if (order == ByteOrder.BigEndian)
                return (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
            else
                return (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
        }
        public static float SwapToSingle(byte[] buf, ByteOrder order)
        {
            if (order == ByteOrder.BigEndian)
            {
                byte[] test = BitConverter.GetBytes((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]);
                return BitConverter.ToSingle(test,0);
            }
            else
            {
                byte[] test = BitConverter.GetBytes((buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0]);
                return BitConverter.ToSingle(test,0);
            }
        }
		public static short SwapToInt16(byte[] buf, ByteOrder order)
		{
            if(order == ByteOrder.BigEndian)
			return (short)((buf[0]<<8) | buf[1]);
        else
			return (short)((buf[1]<<8) | buf[0]);
		}
		public static void ByteSwap(byte[] bytes)
		{
			Array.Reverse(bytes);
		}

		public static string ReverseString(string str)
		{
			char[] characters = new char[str.Length];
			for(int x = 0; x < str.Length; x++)
				characters[str.Length - x - 1] = str[x];
			return new string(characters);
		}
	}
	//public sealed class Bitwise
	//{
	//    public static short SetFlag(short a, short b)
	//    {
	//        return (short)(a | b);
	//    }

	//    public static short UnsetFlag(short a, short b)
	//    {
	//        return a & (~b);
	//    }

	//    // Works with "None" as well
	//    public static bool HasFlag(short a, short b)
	//    {
	//        return (a & b) == b;
	//    }

	//    public static short ToogleFlag(short a, short b)
	//    {
	//        return a ^ b;
	//    }
	//}
}
